package app.serialport;

import java.util.Set;


public class HardwareApiTest {
	
	private static HardwareApiTest instance;
	
	public static synchronized HardwareApiTest getInstance() {
		if(instance == null) {
			instance = new HardwareApiTest();
		}
		return instance;
	}
	
	private SerialPort serialPort;

	private boolean isConnect;
	
	private HardwareApiTest() {
	}
	
	public boolean isConnect() {
		return isConnect;
	}
	
	public synchronized String connect() {
		if(this.isConnect) {
			return "";
		}
		
		SerialPortConfig serialPortConfig = new SerialPortConfig();
		Set<String> availableSerialPorts = SerialPort.getAvailableSerialPorts();
		System.out.println("串口："+availableSerialPorts);
//		port=COM5,baudRate=115200,timeOut=60000
		serialPortConfig.setPort(availableSerialPorts.toArray()[0]+"");
		serialPortConfig.setBaudRate(9600);
		serialPortConfig.setTimeOut(5000);
		
		try {
			serialPort = new SerialPort(serialPortConfig);
			this.isConnect = serialPort.connect();
			if(!isConnect) {
				throw new Exception("打开串口失败");
			}
		} catch (Exception e1) {
		}
		
		serialPort.setDefaultDecoder(new FixedLengthDecoder(7));
		
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		
		return "";
	}
	
	public static void main(String[] args) {
		
		Set<String> availableSerialPorts = SerialPort.getAvailableSerialPorts();
		System.out.println(availableSerialPorts);
		
		HardwareApiTest.getInstance().connect();
		
		while(true) {
			try {
				Thread.sleep(2000);
				HardwareApiTest.getInstance().readData();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
			//HardwareApiTest.getInstance().disconnect();
	}
	
	public int readData() {
		try {
			String command = "";
			byte[] responseData = serialPort.sendDataAwait(command);
			String temp = ByteUtil.bytes2HexString(responseData);
			String data = temp.substring(0, temp.indexOf("2C"));
			System.out.println("--"+data+"--");
			String[] numArray = data.split(" ");
			String num = "";
			for (int i = 0; i < numArray.length; i++) {
				num+=ByteUtil.hexToString(numArray[i]);
			}
			System.out.println(num);
			return new Integer(num);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return 0;
	}
	
	public void disconnect() {
		serialPort.disconnect();
	}
	
	/**
	 * 读板卡号
	 * @return
	 */
//	public List<Board> readBoards() {
//		List<Board> result = new ArrayList<>();
//		
//		String command = "7E 00 7E A1";
//		byte[] responseData = serialPort.sendDataAwait(command);
//		// 8A 8A 81 81(0-3) [data] 8B 8B
//		for (int i = 4; i < responseData.length - 2; ) {
//			String status = ByteUtil.bytes2HexString(responseData[i]);
//			String temp = ByteUtil.bytes2BinaryStr(responseData[i+1]);
//			int cell = Integer.parseInt(temp.substring(0, 4), 2);
//			int boardNo = Integer.parseInt(temp.substring(4, 8), 2);
//			
//			Board board = new Board();
//			board.setCell(cell);
//			board.setNo(boardNo);
//			board.setFine("00".equals(status));
//			
//			result.add(board);
//			
//			i = i + 2;
//		}
//		
//		readBoardPins(result);
//		
//		Set<String> connections = readBoardConnections();
//		for (String connection : connections) {
////			System.out.println("=====connection:" + connection);
//			Color color = ColorUtil.randomHSBColor();
//			String[] pinStrs = connection.split(",");
//			for (String pinStr : pinStrs) {
//				//cell + "-" + boardNo + "-" + address
//				String[] temp =  pinStr.split("-");
//				int cell = Integer.parseInt(temp[0])-1;
//				int boardNo = Integer.parseInt(temp[1])-1;
//				int address = Integer.parseInt(temp[2])-1;
//				
//				for (Board board : result) {
//					for (Pin pin : board.getPins()) {
//						if(pin.getCell() == cell && pin.getBoardNo() == boardNo && pin.getNo() == address) {
//							pin.setColor(color);
//						}
//					}
//				}
//			}
//		}
//		
//		return result;
//	}
//	
	/** 
	 * 二进制字符串转byte 
	 */  
	public static byte binaryStringToByte(String byteStr) {  
	    int re, len;  
	    if (null == byteStr) {  
	        return 0;  
	    }  
	    len = byteStr.length();  
	    if (len != 4 && len != 8) {  
	        return 0;  
	    }  
	    if (len == 8) {// 8 bit处理  
	        if (byteStr.charAt(0) == '0') {// 正数  
	            re = Integer.parseInt(byteStr, 2);  
	        } else {// 负数  
	            re = Integer.parseInt(byteStr, 2) - 256;  
	        }  
	    } else {// 4 bit处理  
	        re = Integer.parseInt(byteStr, 2);  
	    }  
	    return (byte) re;  
	} 
	
	public static int binaryStringToInt(String byteStr) {  
	    int re, len;  
	    if (null == byteStr) {  
	        return 0;  
	    }  
	    len = byteStr.length();  
	    if (len != 4 && len != 8) {  
	        return 0;  
	    }  
	    if (len == 8) {// 8 bit处理  
	        if (byteStr.charAt(0) == '0') {// 正数  
	            re = Integer.parseInt(byteStr, 2);  
	        } else {// 负数  
	            re = Integer.parseInt(byteStr, 2) - 256;  
	        }  
	    } else {// 4 bit处理  
	        re = Integer.parseInt(byteStr, 2);  
	    }  
	    return re;  
	} 
	
}
